package com.xgq.drink.websocket;
import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xgq.drink.entity.ChatAttachment;
import com.xgq.drink.mapper.ChatAttachmentMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.stereotype.Controller;

import java.util.*;

import com.xgq.drink.config.KafkaConfig;
import org.springframework.kafka.core.KafkaTemplate;
/**
 * WebSocket消息处理器
 * 用于处理WebSocket消息路由和分发
 */
@Slf4j
@Controller
public class WebSocketMessageHandler {

    @Autowired
    private ChatAttachmentMapper chatAttachmentMapper;
    @Autowired
    private KafkaTemplate<String, Object> kafkaTemplate;
    private String getFileType(String fileUrl) {
        if (fileUrl == null) return "unknown";
        int lastDotIndex = fileUrl.lastIndexOf('.');
        return lastDotIndex != -1 ? fileUrl.substring(lastDotIndex + 1) : "unknown";
    }
    private static final Snowflake SNOWFLAKE = new Snowflake(1, 1); // 需要引入或实现雪花算法

    // 修改私聊消息处理
    @MessageMapping("/chat.private")
    public void handlePrivateMessage(@Payload Map<String, Object> message, SimpMessageHeaderAccessor headerAccessor) {
        try {
            log.info("收到用户的私聊消息: {}", message);
            String userId = message.get("senderId").toString();
            Long senderId = Long.valueOf(Objects.toString(message.get("senderId"), ""));
            Long receiverId = Long.valueOf(Objects.toString(message.get("receiverId"), ""));
            if (senderId == 0L || receiverId == 0L) {
                log.error("非法消息参数: {}", message);
                return;
            }
            List<ChatAttachment> attachmentList = new ArrayList<>();
            // 2. 处理附件（当消息类型不为1时）
            Long messageId = SNOWFLAKE.nextId();
            Integer messageType = (Integer) message.get("messageType");
            log.info("私聊消息类型: {}", messageType);
            if (messageType != 1) {
                List<Map<String, Object>> attachments = (List<Map<String, Object>>) message.get("attachments");
                if (attachments.size()>0) {
                    for (Map<String, Object> attachment : attachments) {
                        Map<String, Object> response = (Map<String, Object>) attachment.get("response");
                        if (response != null) {
                            ChatAttachment chatAttachment = new ChatAttachment();
                            chatAttachment.setMessageId(messageId);
                            chatAttachment.setFileName((String) attachment.get("name"));
                            chatAttachment.setFileUrl((String) response.get("data"));
                            chatAttachment.setFileType(getFileType((String) response.get("data")));
                            chatAttachment.setFileSize(Long.valueOf(attachment.get("size").toString()));
                            attachmentList.add(chatAttachment);
                        }
                    }
                    for (ChatAttachment attachment : attachmentList) {
                        System.out.println("Attachment: " + attachment);
                        chatAttachmentMapper.insert(attachment);
                    }
                }
            }

            // 构建消息对象
            Map<String, Object> msg = new HashMap<>();
            msg.put("type", "PRIVATE_MESSAGE");
            msg.put("messageId", messageId);
            msg.put("senderId", userId);
            msg.put("receiverId", receiverId);
            msg.put("content", Objects.toString(message.get("content"), ""));
            msg.put("status", 0);
            msg.put("messageType", messageType);
            msg.put("timestamp", System.currentTimeMillis());

            if (messageType != 1) {
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("message_id", messageId);
                msg.put("attachments",chatAttachmentMapper.selectList(queryWrapper));
            } else {
                msg.put("attachments", Collections.emptyList());
            }

            // 发送到Kafka
            kafkaTemplate.send(KafkaConfig.TOPIC_PRIVATE_CHAT, msg);
        } catch (Exception e) {
            log.error("处理私聊消息时出错", e);
        }
    }
    // 修改群聊消息处理
    @MessageMapping("/chat.group")
    public void handleGroupMessage(@Payload Map<String, Object> message, SimpMessageHeaderAccessor headerAccessor) {
        log.info("收到群聊消息: {}", message);
        try {
            String userId = message.get("senderId").toString();
            String groupId = message.get("groupId").toString();
            // 构建消息对象
            Map<String, Object> msg = Map.of(
                "type", "GROUP_MESSAGE",
                "messageId", UUID.randomUUID().toString(),
                "groupId", groupId,
                "senderId", userId,
                "content", message.get("content"),
                "status", 0,
                "timestamp", System.currentTimeMillis(),
                "files", message.get("files")
            );

            // 发送到Kafka
            kafkaTemplate.send(KafkaConfig.TOPIC_GROUP_CHAT, msg);
        } catch (Exception e) {
            log.error("处理群聊消息时出错", e);
        }
    }
    /**
     * 处理消息状态更新
     */
    @MessageMapping("/chat.status")
    public void handleStatusUpdate(@Payload Map<String, Object> statusUpdate, SimpMessageHeaderAccessor headerAccessor) {
        try {
            String userId = String.valueOf(Objects.requireNonNull(headerAccessor.getSessionAttributes()).get("userId"));
            log.info("收到用户 {} 的状态更新: {}", userId, statusUpdate);

            // 根据状态更新类型处理
            String type = statusUpdate.get("type").toString();

            if ("READ_RECEIPT".equals(type)) {
                // 处理已读回执
                String messageId = statusUpdate.get("messageId").toString();
                String senderId = statusUpdate.get("senderId").toString();

                // 通知消息发送者该消息已被阅读
//                kafkaTemplate.send(KafkaConfig.TOPIC_STATUS_UPDATE, statusUpdate);

                log.info("已发送消息 {} 的已读回执给用户 {}", messageId, senderId);
            }
        } catch (Exception e) {
            log.error("处理状态更新时出错", e);
        }
    }
}
